package com.ethink.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.db.PageUtils;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.id.generator.IdGenerator;
import com.ethink.order.api.enums.SaleOrderOrderStatusEnum;
import com.ethink.order.api.info.SaleDetailOrderInfo;
import com.ethink.order.api.info.SaleOrderInfo;
import com.ethink.order.api.model.SaleDetailOrderModel;
import com.ethink.order.api.model.SaleOrderModeQueryModel;
import com.ethink.order.api.model.SaleOrderPageQueryModel;
import com.ethink.order.api.request.SaleOrderAddRequest;
import com.ethink.order.api.request.SaleOrderModeQueryRequest;
import com.ethink.order.api.request.SaleOrderQueryRequest;
import com.ethink.order.api.request.SaleOrderUpdateStatusRequest;
import com.ethink.order.api.response.SaleOrderAddResponse;
import com.ethink.order.api.response.SaleOrderDetailResponse;
import com.ethink.order.common.entity.SaleOrder;
import com.ethink.order.common.mapper.SaleDetailOrderMapper;
import com.ethink.order.common.mapper.SaleOrderMapper;
import com.ethink.order.converter.SaleOrderConverter;
import com.ethink.order.manager.SaleChannelRequestManager;
import com.ethink.order.service.SaleDetailOrderService;
import com.ethink.order.service.SaleOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * TOC销售单 Service接口实现
 *
 * @author default
 * @date 2022-11-22
 */
@Slf4j
@Service
public class SaleOrderServiceImpl implements SaleOrderService {

    @Autowired
    private SaleOrderMapper saleOrderMapper;

    @Autowired
    private SaleOrderConverter saleOrderConverter;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private SaleDetailOrderService saleDetailOrderService;

    @Autowired
    private SaleDetailOrderMapper saleDetailOrderMapper;

    @Override
    public SaleOrderAddResponse addSaleOrder(SaleOrderAddRequest request, Boolean isSelect) {
        String orderNo = idGenerator.xs();
        request.setOrderNo(orderNo);
        SaleOrder saleOrder = new SaleOrder();
        BeanUtils.copyProperties(request, saleOrder, "item");
        int insert = saleOrderMapper.insert(saleOrder);
        //保存商品信息
        saleDetailOrderService.batchInsert(request.getItem(), orderNo, request.getExchangeRate());
        SaleOrderAddResponse response = new SaleOrderAddResponse();
        response.setSaleOrderInfo(saleOrderConverter.convertFrom(saleOrder));
        if (isSelect) {
            response.setSaleDetailOrderInfoList(saleDetailOrderMapper.selectByOrderNo(saleOrder.getOrderNo()));
        }
        return response;
    }

    @Override
    public Page<SaleOrderPageQueryModel> pageQuerySaleOrder(SaleOrderQueryRequest request) {
        SaleChannelRequestManager.fill(request, 0, 1, 2);
        return saleOrderMapper.pageQuery(PageUtils.buildPage(request), request);
    }

    @Override
    public Integer deleteSaleOrder(Long id) {
        SaleOrder saleOrder = saleOrderMapper.selectById(id);
        if (!SaleOrderOrderStatusEnum.S1.getIntValue().equals(saleOrder.getOrderStatus())) {
            throw new BusinessException(CommonRespCode.SYSTEM_ERR.getCode(), "仅草稿状态删除");
        }
        return saleOrderMapper.delById(id);
    }

    @Override
    public SaleOrderDetailResponse getSaleOrderById(Long id) {
        SaleOrderDetailResponse response = new SaleOrderDetailResponse();
        SaleOrder saleOrder = saleOrderMapper.selectById(id);
        if (ObjectUtil.isEmpty(saleOrder)) {
            return response;
        }
        SaleOrderInfo saleOrderInfo = saleOrderConverter.convertFrom(saleOrder);
        response.setMain(saleOrderInfo);
        List<SaleDetailOrderModel> item = saleDetailOrderMapper.selectByOrderNo(saleOrder.getOrderNo());
        response.setItem(item);
        //合计统计
        BigDecimal totalPrice = BigDecimal.ZERO;
        Integer totalNum = 0;
        for (SaleDetailOrderModel saleDetailOrderModel : item) {
            totalPrice = totalPrice.add(saleDetailOrderModel.getSumPrice());
            totalNum += saleDetailOrderModel.getOutQty();
        }
        response.setTotalNum(totalNum);
        response.setTotalPrice(totalPrice);
        return response;
    }

    @Override
    public Integer updateStatus(SaleOrderUpdateStatusRequest request) {
        return saleOrderMapper.update(null, new LambdaUpdateWrapper<SaleOrder>()
                .eq(SaleOrder::getId, request.getId())
                .set(SaleOrder::getOrderStatus, request.getOrderStatus())
        );
    }

    @Override
    public SaleOrderDetailResponse getSaleOrderByOrderNo(String orderNo) {
        SaleOrderDetailResponse response = new SaleOrderDetailResponse();
        SaleOrder saleOrder = saleOrderMapper.selectOne(
                new LambdaQueryWrapper<SaleOrder>().eq(SaleOrder::getOrderNo, orderNo));
        if (ObjectUtil.isEmpty(saleOrder)) {
            return response;
        }
        SaleOrderInfo saleOrderInfo = saleOrderConverter.convertFrom(saleOrder);
        response.setMain(saleOrderInfo);
        List<SaleDetailOrderModel> item = saleDetailOrderMapper.selectByOrderNo(saleOrder.getOrderNo());
        response.setItem(item);
        //合计统计
        BigDecimal totalPrice = BigDecimal.ZERO;
        Integer totalNum = 0;
        for (SaleDetailOrderModel saleDetailOrderModel : item) {
            totalPrice = totalPrice.add(saleDetailOrderModel.getSumPrice());
            totalNum += saleDetailOrderModel.getOutQty();
        }
        response.setTotalNum(totalNum);
        response.setTotalPrice(totalPrice);
        return response;
    }

    @Override
    public Boolean saleOrderStatusFinish(List<String> orderNo) {
        if (CollUtil.isEmpty(orderNo)) {
            return true;
        }
        return saleOrderMapper.update(null, new LambdaUpdateWrapper<SaleOrder>()
                .in(SaleOrder::getOrderNo, orderNo)
                .set(SaleOrder::getOrderStatus, SaleOrderOrderStatusEnum.S4.getIntValue())
        ) > 0;
    }

    @Override
    public List<SaleDetailOrderInfo> queryDetailByTobOrderNo(String orderNo) {
        return saleDetailOrderMapper.queryDetailByTobOrderNo(orderNo);
    }

    /**
     * 分页查询
     *
     * @param request
     * @return
     */
    @Override
    public Page<SaleOrderModeQueryModel> pageSaleOrderModeQuery(SaleOrderModeQueryRequest request) {
        SaleChannelRequestManager.fill(request, 3, 4, 5);
        return saleOrderMapper.pageSaleOrderModeQuery(PageUtils.buildPage(request), request);
    }

    @Override
    public SaleOrderDetailResponse getSaleOrderByShopOrderNo(String saleSubChannel,String shopOrderNo) {
        SaleOrderDetailResponse saleOrderDetailResponse = new SaleOrderDetailResponse();
        SaleOrder saleOrder = saleOrderMapper.selectOne(new LambdaQueryWrapper<SaleOrder>()
                .eq(SaleOrder::getShopOrderNo, shopOrderNo)
                .eq(SaleOrder::getSaleSubChannel,saleSubChannel));
        SaleOrderInfo saleOrderInfo = saleOrderConverter.convertFrom(saleOrder);
        saleOrderDetailResponse.setMain(saleOrderInfo);
        List<SaleDetailOrderModel> item = saleDetailOrderMapper.selectByOrderNo(saleOrder.getOrderNo());
        saleOrderDetailResponse.setItem(item);
        return saleOrderDetailResponse;
    }

    @Override
    public SaleOrderInfo selectSaleOrderById(Integer id) {
        SaleOrder saleOrder = saleOrderMapper.selectById(id);
        return BeanUtil.copyProperties(saleOrder, SaleOrderInfo.class);
    }

}
